import os
import threading
from tkinter import Button

from util.comm.AsyncTask import AsyncTask
from util.comm.msg_util import msg
from util.database.cmd import run_cmd
from util.comm.path import getPath


def create_config_button(self, refresh=False):
    if refresh and ~hasattr(self, 'elements'):
        self.elements = []
    self.button = Button(self.tab, text='⚙', command=lambda s=self,r=refresh: change_config_sync(s, r))
    self.button.pack(side='right', fill=None, expand=False, anchor='ne')
    if refresh:
        self.elements.append(self.button)
    return self.button

def change_config_sync(self, r):
    if hasattr(self, 'config_sync_flag') and self.config_sync_flag == '1':
        msg('已经打开配置文件,请勿重复操作')
        return
    self.config_sync_flag = '1'
    AsyncTask(threading.Thread(target=change_config, args=(self, r,)), lambda s=self: reset_sync(s)).execute_async()

def reset_sync(self):
    self.config_sync_flag = '0'

def change_config(self, refresh):
    run_cmd(f"notepad {self.config_path}")
    if refresh:
        for element in self.elements:
            element.destroy()
        self.frame(self.tab)